<template>
  <div v-if="showSettingInternal" class="gadget_query_model">
    <el-dialog
      :visible="showSettingInternal&&flag"
      class="queryModelDialog"
      width="98%"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :modal="true"
      :before-close="cancelReport"
      :title="$t('custom.report.gaugebuilder')"
      append-to-body
    >
      <el-row :gutter="0">
        <el-col :span="7">
          <div id="tabsList" v-loading="loading">
            <el-tabs
              tab-position="left"
              @tab-click="tabClick"
              :before-leave="onchangeTabs"
              v-model="defaultTab"
              style=""
            >
              <el-tab-pane
                name="info"
                class="section-setting scroll-css tabs-pane-padding"
              >
                <span slot="label">
                  <el-tooltip
                    :open-delay="1000"
                    effect="dark"
                    placement="left"
                    :content="$t('model.info')"
                  >
                    <img
                      class="el-icon"
                      size="24px"
                      src="../../../assets/mspbots/query-model/querymodelinfo.png"
                    />
                  </el-tooltip>
                </span>
                <h3 style="margin: 0px 0px 5px 0px">
                  {{ $t('model.basicsetting') }}
                </h3>
                <el-form
                  ref="dataForm"
                  :rules="dataRule"
                  :model="dataInfoCopy"
                  style="padding: 0px 10px 0px 0px"
                >
                  <el-form-item
                    :label="$t('custom.reports.title')"
                    prop="name"
                    class="is-must-object"
                    style="position: relative"
                  >
                    <el-input
                      :placeholder="$t('custom.reports.gaugeNamePlaceholder')"
                      size="small"
                      maxlength="100"
                      v-model="dataInfoCopy.name"
                    ></el-input>
                  </el-form-item>
                  <el-form-item
                    :label="$t('custom.reports.description')"
                    prop="description"
                    style="margin-top: 20px"
                  >
                    <el-input
                      :placeholder="$t('custom.reports.enterdescription')"
                      size="small"
                      type="textarea"
                      maxlength="500"
                      @input="inputDescriptionChange"
                      :rows="10"
                      v-model="dataInfoCopy.description"
                    ></el-input>
                  </el-form-item>
                  <el-form-item :label="$t('custom.reports.wikiUrl')">
                    <el-input
                      :placeholder="$t('custom.reports.enterwikiurl')"
                      size="small"
                      type="text"
                      @input="inputDescriptionChange"
                      v-model="dataInfoCopy.wikiUrl"
                    ></el-input>
                  </el-form-item>
                  <el-form-item
                    class="is-must-object"
                    style="position: relative"
                    :label="$t('custom.reports.role')"
                  >
                    <el-select
                      v-model="dataInfoCopy.roleIdList"
                      filterable
                      clearable
                      multiple
                      collapse-tags
                      default-first-option
                      :placeholder="$t('custom.dataset.role')"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="(its, iii) in fullRoleList"
                        :key="iii"
                        :label="its.name"
                        :value="its.roleId"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    prop="tagList"
                    :label="$t('custom.reports.tag')"
                  > 
                    <el-select
                      v-model="dataInfoCopy.tagList"
                      filterable
                      clearable
                      multiple
                      allow-create
                      collapse-tags
                      default-first-option
                      :placeholder="$t('custom.reports.tag')"
                      style="width: 100%"
                      :loading="tagLoading"
                    >
                      <el-option
                        v-for="(its, iii) in tags"
                        :key="iii"
                        :label="its.name"
                        :value="its.name"
                      >
                      <div style="display: flex;justify-content:space-between;">
                        <ZTooltip :content="its.name"
                           :line="1"
                          placement="top">
                            <span style="flex:1">{{ its.name }}</span>
                        </ZTooltip>
                        <span>
                          <el-button 
                                       style="float: right;font-size: 14px;margin-top: 3px;margin-left: 10px;"
                                       size='mini'
                                       type="text"
                                       @click.stop="deleteTag(its)">
                              <i class="cuifont icon_delete"
                                 style="font-size:14px;color:#CCC"></i>
                            </el-button>
                        </span>
                      </div>
                    </el-option>
                    </el-select>
                  </el-form-item>
                  <!-- <el-form-item label="Picture"
                                v-if="dataInfoCopy.id">
                    <ZHighUpload v-model="filePath"
                                 :id="dataInfoCopy.id"
                                 :resourceType="1"
                                 :file-list="getSnapshot"
                                 :after-upload="depositSnapshot" />
                  </el-form-item> -->
                </el-form>
                <div>
                  <el-row>
                    <el-col :span="24" class="info-tips">
                      <div style="width: 314px; display: flex">
                        <i
                          class="el-icon-info"
                          style="
                            width: 11px;
                            height: 11px;
                            color: #7f7f7f;
                            margin-top: 4px;
                            opacity: 0.5;
                          "
                        ></i>
                        <span
                          style="
                            flex: 1;
                            width: 303px;
                            margin-left: 5px;
                            font-size: 12px;
                            font-weight: 400;
                            color: #7f7f7f;
                            line-height: 18px;
                          "
                        >
                          <span style="opacity: 0.5"
                            >{{ $t('model.integration') }} :</span
                          >
                          <span
                            v-for="(
                              item, index
                            ) in dataInfoCopy.integrationCode"
                            :key="item"
                          >
                            <span style="opacity: 0.5" v-if="isLinked(item)">{{
                              findName(item)
                            }}</span>
                            <el-link
                              v-else
                              style="font-size: 12px"
                              @click="goToIntegration"
                              type="danger"
                              >{{ findName(item) }}</el-link
                            >
                            <span
                              v-if="
                                index !== dataInfoCopy.integration.length - 1
                              "
                              >,&nbsp;&nbsp;</span
                            >
                          </span>
                        </span>
                        <!-- <span v-else style="flex:1;width:303px;margin-left:5px;font-size: 12px;font-weight: 400;color: #7F7F7F;line-height: 18px"><span style="opacity: 0.5">{{$t('model.integration')}}</span> : <el-link style="font-size: 12px;" type="danger">{{formatList(dataInfoCopy.integration)}}</el-link></span> -->
                      </div>
                    </el-col>
                    <el-col :span="24" class="info-tips">
                      <div style="width: 314px; display: flex; opacity: 0.5">
                        <i
                          class="el-icon-info"
                          style="
                            width: 11px;
                            height: 11px;
                            color: #7f7f7f;
                            margin-top: 4px;
                          "
                        ></i>
                        <span
                          style="
                            flex: 1;
                            width: 303px;
                            margin-left: 5px;
                            font-size: 12px;
                            font-weight: 400;
                            color: #7f7f7f;
                            line-height: 18px;
                          "
                          >{{ $t('model.dataset') }} :
                          {{ formatList(dataInfoCopy.dataset) }}</span
                        >
                      </div>
                    </el-col>
                    <el-col :span="24">
                      <el-button
                        @click="showMoreClick"
                        v-if="hasMoreEditPermission"
                        style="margin-left: 15px; padding-top: 0"
                        type="text"
                        ><u style="font-size: 12px">{{
                          $t('model.moreedit')
                        }}</u></el-button
                      >
                    </el-col>
                  </el-row>
                </div>
              </el-tab-pane>
              <el-tab-pane
                name="dataset"
                el-tab-pane
                class="section-setting scroll-css tabs-pane-padding"
              >
                <span slot="label">
                  <el-tooltip
                    :open-delay="1000"
                    effect="dark"
                    placement="left"
                    :content="$t('model.dataset')"
                  >
                    <img
                      class="el-icon"
                      size="24px"
                      src="../../../assets/mspbots/query-model/querymodeldataset.png"
                    />
                  </el-tooltip>
                </span>
                <el-form
                  :model="dataInfoCopy"
                  :rules="dataRule"
                  label-position="top"
                  ref="report-setting-dataForm"
                  :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'"
                >
                  <!-- ------------------------------------------------------------------ language ------------------------------------------------------------------ -->
                  <el-form-item
                    :label="$t('custom.report.language')"
                    prop="language"
                    v-show="isAdvanceMode"
                  >
                    <el-select v-model="language">
                      <el-option
                        v-for="(e, index2) in languageList"
                        :key="index2"
                        :label="e.label"
                        :value="e.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <div v-if="language === 1 || language === 2">
                    <querysql :dataInfo="dataInfoCopy"></querysql>
                  </div>
                  <div v-if="language === 3 || language === 4">
                    <querydataset
                      :parentSlicer="thisSlicer"
                      :dataInfo="dataInfoCopy"
                      :selectFields="selectFields"
                      :defaultDataset="defaultDataset"
                      @primaryDataChange="updateformSelectList"
                      @previewData="saveReport"
                      @datasetChange="onDatasetChange"
                      @allFieldsList="allFieldsList"
                      @getQueryList="getQueryList"
                      ref="querydataset"
                    ></querydataset>
                  </div>
                  <div
                    v-if="language === 2"
                    :label="$t('custom.report.groovysetting')"
                  >
                    <querygroovy :dataInfo="dataInfoCopy"></querygroovy>
                  </div>
                  <el-divider></el-divider>
                  <el-form-item :label="$t('model.orderby')">
                    <ColumnsOrderBy
                      ref="order-by"
                      :qureyInfo="qureyInfo"
                      :orderByFieldsList="orderbyList"
                    ></ColumnsOrderBy>
                  </el-form-item>
                  <el-divider></el-divider>
                  <el-form-item :label="$t('model.rowlimit')">
                    <ColumnsLimit
                      ref="row-limit"
                      :qureyInfo="qureyInfo"
                      :width="100"
                    ></ColumnsLimit>
                  </el-form-item>
                  <el-divider></el-divider>
                  <el-form-item>
                    <div>
                      <el-tooltip
                        :open-delay="1000"
                        effect="dark"
                        :content="$t('custom.dataInspector')"
                        placement="top"
                      >
                        <el-button
                          @click="showDataInspactor"
                          :disabled="Boolean(!dataInfoCopy.gadgetId)"
                          class="cuifont icon_data_inspactor"
                          style="fontsize: 14px; padding: 7px"
                        ></el-button>
                      </el-tooltip>
                      <PreWiewData
                        ref="preview-data"
                        :gadgetId="dataInfoCopy.gadgetId"
                      />
                    </div>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              <el-tab-pane
                name="config"
                class="section-setting scroll-css tabs-pane-padding"
              >
                <span slot="label">
                  <el-tooltip
                    :open-delay="1000"
                    effect="dark"
                    placement="left"
                    :content="$t('model.config')"
                  >
                    <img
                      class="el-icon"
                      size="24px"
                      src="../../../assets/mspbots/query-model/querymodelconfig.png"
                    />
                  </el-tooltip>
                </span>
                <div>
                  <gadgetsetting
                    v-if="!loading"
                    ref="gadget-setting"
                    :key="dataInfo.gadgetType"
                    :isAdvanceMode="isAdvanceMode"
                    :dataInfo="dataInfoCopy"
                    :settingType="'config'"
                    @afterInit="afterSettingInit"
                    @updateLayerStatus="updateLayerStatus"
                    @updateDataInfo="
                      e => {
                        dataInfoCopy = Object.assign({}, e)
                      }
                    "
                  ></gadgetsetting>
                </div>
              </el-tab-pane>
              <el-tab-pane
                name="condition"
                class="section-setting scroll-css tabs-pane-padding"
                v-if="
                  dataInfoCopy.gadgetType === 'barchartgadget' ||
                  dataInfoCopy.gadgetType === 'gridgadget' ||
                  dataInfoCopy.gadgetType === 'crudformgadget' ||
                  dataInfoCopy.gadgetType === 'cardnumbergadget' ||
                  dataInfoCopy.gadgetType === 'scorecardgadget' ||
                  dataInfoCopy.gadgetType === 'crudformplusgadget' ||
                  dataInfoCopy.gadgetType === 'chartgridgadget' ||
                  dataInfoCopy.gadgetType === 'litikugadget' ||
                  dataInfoCopy.gadgetType === 'tablegadget' ||
                  dataInfoCopy.gadgetType === 'chartgadget'
                "
              >
                <span slot="label">
                  <el-tooltip
                    :open-delay="1000"
                    effect="dark"
                    placement="left"
                    :content="$t('model.condition')"
                  >
                    <img
                      class="el-icon"
                      size="24px"
                      src="../../../assets/mspbots/query-model/querymodelcondition format.png"
                    />
                  </el-tooltip>
                </span>
                <div>
                  <conditionsetting
                    v-if="dataInfoCopy.gadgetSetting"
                    ref="condition-setting"
                    :dataInfoCondition="dataInfoCopy"
                  ></conditionsetting>
                </div>
              </el-tab-pane>
              <el-tab-pane
                name="snapshot"
                v-if="dataInfoCopy.id &&dataInfoCopy.gadgetType === 'scorecardgadget'">
                <span slot="label">
                  <el-tooltip
                    :open-delay="1000"
                    effect="dark"
                    placement="left"
                    :content="$t('custom.component.gadget.snapshot')"
                  >
                    <img
                      class="el-icon"
                      size="24px"
                      src="../../../assets/mspbots/query-model/snapshot.png"
                    />
                  </el-tooltip>
                </span>
                <div>
                  <snapshotInfo
                    ref="snapshot-info"
                    :dataInfoSnapshot="dataInfoCopy"
                    @cancelReport="cancelReport"
                  ></snapshotInfo>
                </div>
              </el-tab-pane>
              <el-tab-pane
                name="benchMark"
                v-if="dataInfoCopy.gadgetType === 'chartgridgadget'"
                class="section-setting scroll-css tabs-pane-padding"
              >
                <span slot="label">
                  <el-tooltip
                    :open-delay="1000"
                    effect="dark"
                    placement="left"
                    :content="$t('model.benchMark')"
                  >
                    <img
                      class="el-icon"
                      size="24px"
                      src="../../../assets/mspbots/query-model/benchmark.png"
                    />
                  </el-tooltip>
                </span>
                <div>
                  <gadgetsetting
                    v-if="!loading"
                    ref="gadget-setting-benchmark"
                    :key="dataInfo.gadgetType"
                    :isAdvanceMode="isAdvanceMode"
                    :settingType="'benchmark'"
                    :dataInfo="dataInfoCopy"
                    @afterInit="afterSettingInit"
                    @updateLayerStatus="updateLayerStatus"
                    @updateDataInfo="
                      e => {
                        dataInfoCopy = Object.assign({}, e)
                      }
                    "
                  ></gadgetsetting>
                </div>
              </el-tab-pane>
              <el-tab-pane
                name="kpiSettings"
                v-if="dataInfoCopy.gadgetType === 'chartgridgadget'"
                class="section-setting scroll-css tabs-pane-padding"
              >
                <span slot="label">
                  <el-tooltip
                    :open-delay="1000"
                    effect="dark"
                    placement="left"
                    :content="$t('model.kpiSettings')"
                  >
                    <img
                      class="el-icon"
                      size="24px"
                      src="../../../assets/mspbots/query-model/kpi_setting.png"
                    />
                  </el-tooltip>
                </span>
                <div>
                  <gadgetsetting
                    v-if="!loading"
                    :key="dataInfoCopy.gadgetType"
                    ref="gadget-setting-kpisettings"
                    :isAdvanceMode="isAdvanceMode"
                    :settingType="'kpisettings'"
                    :dataInfo="dataInfoCopy"
                    @afterInit="afterSettingInit"
                    @updateLayerStatus="updateLayerStatus"
                    @updateDataInfo="
                      e => {
                        dataInfoCopy = Object.assign({}, e)
                      }
                    "
                  ></gadgetsetting>
                </div>
              </el-tab-pane>
              <el-tab-pane
                name="history"
                class="section-setting scroll-css tabs-pane-padding"
              >
                <span slot="label">
                  <el-tooltip
                    :open-delay="1000"
                    effect="dark"
                    placement="left"
                    :content="$t('model.history')"
                  >
                    <img
                      class="el-icon"
                      size="24px"
                      src="../../../assets/mspbots/query-model/querymodelhistory.png"
                    />
                  </el-tooltip>
                </span>
                <el-table
                  :data="historyVersionList"
                  border
                  tooltip-effect="dark"
                  size="small"
                >
                  <el-table-column
                    :label="$t('custom.reports.tableLabel.code')"
                    prop="id"
                    align="left"
                    show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column
                    :label="$t('custom.reports.tableLabel.createTime')"
                    prop="createTime"
                    align="left"
                    show-overflow-tooltip
                  >
                    <template slot-scope="scope">
                      {{ scope.row.createTime | ClientFormat }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    :label="$t('custom.widget.lastmodified')"
                    prop="updateByName"
                    align="left"
                    show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column
                    :label="$t('custom.reports.tableLabel.action')"
                    align="left"
                    width="140"
                  >
                    <template slot-scope="scope">
                      <el-button
                        size="small"
                        type="text"
                        :disabled="!hasEditPermission"
                        @click="useHistoryVersion(scope.row)"
                        >{{ $t('custom.reports.resetBtn') }}
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-col>
        <el-col :span="17">
          <h3 style="margin: 0px 0px 5px 0px">{{ $t('model.preview') }}</h3>
          <div
            class="section-preview scroll-css relative"
            style="overflow-y: hidden"
          >
            <gadgetpreview
              v-if="showPriview"
              :key="dataInfoCopy.gadgetType"
              ref="gadget-preview"
              @gadgetSettingroupSettingsColumns="
                gadgetSettingroupSettingsColumns
              "
              :dataInfo="dataInfoCopy"
            ></gadgetpreview>
            <!--        -->
          </div>
        </el-col>
      </el-row>
      <div slot="footer" style="text-align-last: auto">
        <el-tooltip
          :open-delay="1000"
          effect="dark"
          placement="left"
          :content="$t('custom.component.gadget.copyShareLink')"
          v-if="dataInfoCopy.id"
        >
          <el-button
            type="warning"
            size="small"
            style="margin-right: 10px"
            @click="shareWidget(dataInfoCopy.id, dataInfoCopy.businessType)"
            icon="el-icon-share"
            circle
          >
          </el-button>
        </el-tooltip>
        <el-link
          type="primary"
          v-if="
            $hasPermission('sys:tenant:model:showadvance') && hasEditPermission
          "
          @click="clickMode"
        >
          {{
            isAdvanceMode
              ? $t('custom.report.regularmode')
              : $t('custom.report.advancemode')
          }}
        </el-link>
        &nbsp;&nbsp;
        <el-button
          size="small"
          type="primary"
          plain
          v-show="false"
          @click="saveGadget"
          >{{ $t('custom.saveAs') }}
        </el-button>
        <el-button size="small" v-if="(dataInfo.id||dataInfoCopy.id) && deleteButtonAuth(dataInfoCopy)" @click="deleteReport"
          >{{ $t('custom.delete') }}
        </el-button>
        <el-button size="small" v-if="(dataInfo.id||dataInfoCopy.id) && cloneButtonAuth(dataInfoCopy)" @click="cloneReport"
          >{{ $t('custom.report.clone') }}
        </el-button>
        <el-button size="small" @click="cancelReport"
          >{{ $t('custom.close') }}
        </el-button>
        <el-button
          type="primary"
          v-if="hasEditPermission"
          size="small"
          @click="applyReport"
          >{{ $t('custom.preview') }}
        </el-button>
      </div>
      <MoreEdit ref="more-edit" :dataInfo="dataInfoCopy"></MoreEdit>
    </el-dialog>
    <LinkedDashboards :visible.sync="linkedDashboardsModalVisible"
                      :gadgetId="curSelected.gadgetId"
                      :resourceType="1"
                      :id="curSelected.id"
                      v-if="linkedDashboardsModalVisible" />

    <LinkedBots :visible.sync="linkedBotsModalVisible"
                :gadgetId="curSelected.gadgetId"
                :resourceType="1"
                v-if="linkedBotsModalVisible" />
    <CloneWidget :visible.sync="cloneWidgetModalVisible"
                :gadgetId="curSelected.gadgetId"
                v-if="cloneWidgetModalVisible"
                :resourceType="1"
                @event:success="refresh" />       
  </div>
</template>

<script>
import querysql from './modules/query-sql'
import querydataset from './modules/query-dataset'
import querygroovy from './modules/query-groovy'
import gadgetsetting from './modules/gadget-setting'
import conditionsetting from './modules/condition-setting'
import settingform from './modules/setting-form'
import MoreEdit from './modules/query-more-edit'
import moment from 'moment'
import {
  defaultGadgetSettingList,
  slicerGadgetTypeList
} from '@/utils/data-json'
import { mergeCoverData, getUrlQureyParams,filterRole } from '@/utils/common'
import ColumnsOrderBy from '@/components/columns/columns-orderby'
import ColumnsLimit from '@/components/columns/columns-limit'
import PreWiewData from '@/components/preview-data/index'
import qs from 'qs'
import { getUUID } from '@/utils'
import snapshotInfo from './modules/query-snapshot-info'
import gadgetpreview from './modules/gadget-preview'
import Emitter from '@/mixins/emitter'
import ZHighUpload from '@/components/storybook/z-upload/src/z-high-upload'
import Snapshot from '@/components/storybook/mixins/snapshot'
import { InterceptContext } from '@/components/storybook/s-Intercept/intercept-context'
import LinkedDashboards from '@/views/modules/widget/components/linked-dashboards'
import LinkedBots from '@/components/storybook/b-linked-bots'
import CloneWidget from '@/views/modules/widget/components/clone-widget'
import useErrorMessage from '@/components/storybook/hooks/useErrorMessage'
import ZTooltip from '@/components/storybook/z-tooltip'
import { deleteTag } from '@/api/new'
import bus from '@/components/storybook/utilties/bus'

export default {
  name: 'QueryModel',
  mixins: [Emitter, Snapshot],
  components: {
    querysql,
    querydataset,
    querygroovy,
    gadgetsetting,
    conditionsetting,
    settingform,
    gadgetpreview,
    MoreEdit,
    ColumnsOrderBy,
    ColumnsLimit,
    PreWiewData,
    snapshotInfo,
    ZHighUpload,
    LinkedDashboards,
    LinkedBots,
    CloneWidget,
    ZTooltip
  },
  provide() {
    return {
      isQueryModel: () => this.showSetting
    }
  },
  props: {
    isUserCloneTemplate: {
      type: Boolean,
      default: false
    },
    showSetting: {
      type: Boolean,
      default: false
    },
    dataInfo: {
      type: Object,
      default: function () {
        return {}
      }
    },
    resourceType: [String, Number],
    updateGadget: {
      type: Function,
      default: null
    },
    generateSetting: {
      type: Function,
      default: null
    },
    slicer: {
      type: Object,
      default: function () {
        return {}
      }
    },
    defaultDataset: {
      type: Object,
      default: () => ({})
    },
  
    isAI:Boolean,
  },
  data() {
    return {
      groupSettingsColumns: [],
      storageDeleteDataSetHead: '',
      errorSqlVisible: false,
      drawer: true,
      defaultTab: 'info',
      loading: true,
      flag: true,
      tabLoading: false,
      showPriview: false,
      showSettingInternal: this.showSetting,
      showMoreEditSetting: this.showMoreEditSetting
        ? this.showMoreEditSetting
        : false,
      language: 3, // 1 sql   2 grouvy   3 dataset 4 ai
      languageList: [
        {
          label: 'SQL',
          value: 1
        },
        // {
        //   label: 'Grouvy',
        //   value: 2
        // },
        {
          label: 'Dataset',
          value: 3
        }
      ],
      dataInfoCopy: {
        gadgetSetting: {}
      },
      isAdvanceMode: false,
      activeTab: 'second',
      // datacom: querysql
      modelId: null,
      historyVersionList: [],
      fieldsList: [],
      fieldsLoading: false,
      roleList: [],
      saveSource: '',
      isNameOk: true,
      isNew: true,
      gadgetId: '',
      rules: {
        name: [
          {
            validator: this.validatePass,
            trigger: 'blur',
            pattern: '[^ \x22]+'
          }
        ]
      },
      countNumber: 0,
      originDatasetId: null,
      locationURL: window.location,
      widgetIdLink: getUrlQureyParams('widgetId'),
      isNewAdd: false,
      qureyInfo: {
        orderBy: [],
        rowLimit: ''
      },
      orderbyList: [],
      IsChanged: false,
      selectFields: [],
      assignRoleList: [],
      resRoleList: [],
      queryList: [],
      tags: [],
      filePath: undefined,
      linkedDashboardsModalVisible: false,
      linkedBotsModalVisible: false,
      cloneWidgetModalVisible: false,
      curSelected:{},
      fullRoleList:[],
      tagLoading: false,
    }
  },
  created() {
    this.$root.eventBus.$on('close', (data) => {
      this.cancelReport(data)
    })
    this.$on('event:setting', setting => {
      this.dataInfoCopy.gadgetSetting = setting
    })
    this.$on('event:data-info',  dataInfo => {
      this.dataInfoCopy = dataInfo
     
        this.$nextTick(async ()=>{
          if(this.$refs['gadget-setting']){
            if(this.dataInfoCopy.gadgetType === 'cardnumbergadget'){
              this.$refs['gadget-setting'].initCompanent()
              await this.$refs['gadget-setting'].getDefaultFormSetting()
            }
            this.$refs['gadget-setting'].resetData()    
          }
        })
      
    })
  },
  beforeDestroy () {
    this.$off('event:setting')
    this.$off('event:data-info')
  },
  mounted() {
    // if (!window.location.pathname.includes('/publicReport') && !window.location.pathname.includes('/publicReportPdf')) {
    //   this.getPaidProduct()
    // }
  },
  computed: {
    dataRule() {
      return {
        name: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur',
            pattern: '[^ \x22]+'
          },
          {
            min: 0,
            max: 99,
            message: this.$t('custom.tips.valueLength', { length: '100' }),
            trigger: 'change'
          },
          { validator: this.validatePass, trigger: 'blur' }
        ],
        description: [
          {
            required: false,
            min: 0,
            max: 499,
            message: this.$t('custom.tips.valueLength', { length: '500' }),
            trigger: 'change'
          }
        ]
      }
    },
    thisSlicer() {
      return this.slicer
    },
    datasetOrderBy() {
      try {
        return this.dataInfoCopy.gadgetSetting.datasetOrderBy || []
      } catch (error) {
        return []
      }
    },
    hasEditPermission() {
      let isCustom = this.dataInfoCopy.businessType === 'Custom' ? 1 : 0
      let widgetadmin = this.$hasPermission('sys:widget:widgetadmin') ? 1 : 0
      let editAuth = this.$hasPermission('sys:widget:edit') ? 1 : 0
      if (widgetadmin + editAuth + isCustom >= 2) {
        return true
      } else {
        if (!this.dataInfoCopy.id && editAuth) {
          return true
        }
        return false
      }
    },
    hasMoreEditPermission() {
      return Boolean(this.$hasPermission('sys:widget:moreedit'))
    }
  },
  watch: {
    showSetting: function (val) {
      this.showSettingInternal = val
      if (val) {
        this.defaultTab = 'info'
        this.modelId = null
        this.isAdvanceMode = false
        this.dataInfoCopy = Object.assign(
          {
            name:
              'widget_' +
              moment().utc().format('YY/MM/DD HH:mm') +
              '_' +
              this._.random(1000, 9999, false),
            roleIdList: this.$store.state.roleList,
          },
          this.dataInfo
        )

        if(this.dataInfo.gadgetType === 'AIChartGadget'){
          this.language = 4
          this.dataInfoCopy.language = 4
        }

        this.getRoleAssignList().then(() => {
          this.getReportSetting()
        })
        this.getTags()
        this.IsChanged = false
      } else {
        this.$root.eventBus.$emit('bus:tag-refresh')
      }
    },
  },
  methods: {

    deleteButtonAuth (item) {
      if (item.type === 100101 && item.stc !== this.$store.state.user.tenantCode) {
        return false
      }
      let reportadmin = this.$hasPermission(`sys:widget:widgetadmin`) ? 1 : 0
      let deleteAuth = this.$hasPermission(`sys:widget:delete`) ? 1 : 0
      let isCustom = item.businessType === 'Custom' ? 1 : 0
      if (reportadmin + deleteAuth + isCustom >= 2) {
        return true
      } else {
        return false
      }
    },
    cloneButtonAuth (item) {
      if (item.type === 100101 && item.stc === this.$store.state.user.tenantCode) {
        return false
      }
      return this.$hasPermission(`sys:widget:clone`)
    },
    async getPaidProduct() {
      try {
        const { getPaidProduct } = this.$interface.pay
        const { data: response } = await getPaidProduct()
        if (response.code !== 0) {
          throw response.msg
        }
        InterceptContext.paidProducts = response.data
      } catch (error) {}
    },
    goToIntegration() {
      this.showSettingInternal = false
      this.$emit('queryModelClosed', this.showSettingInternal)
      this.$router.push({ name: 'mspbots-Integrations-index' })
    },
    findName(val) {
      try {
        return this.$store.state.user.integrationList.find(
          item => item.subjectCode === val
        ).name
      } catch (error) {
        return ''
      }
    },
    isLinked(val) {
      var arr = this._.filter(
        this._.filter(this.$store.state.user.integrationList, { group: 1 }),
        { subjectCode: val }
      )
      return arr.length > 0
    },
    gadgetSettingroupSettingsColumns(val) {
      if (val) this.groupSettingsColumns = val
    },
    tabClick() {
   
      if (this.$refs['condition-setting']) {
        this.$refs['condition-setting'].closeDialog &&
          this.$refs['condition-setting'].closeDialog()
      }
    },
    allFieldsList(data) {
      let tempData = []
      if (data.length > 0) {
        for (let index = 0; index < data.length; index++) {
          tempData.push({
            alias: data[index].name,
            fields: data[index].name
          })
        }
      }
      this.orderbyList = tempData
      this.setFieldsList(data)
    },
    getQueryList(data) {
      this.queryList = data
    },
    checkName() {
      this.$refs.dataForm.rules.name[0]['validator'] = this.validatePass
    },
    updateLayerStatus(data) {
      this.$refs['querydataset'].updateLayerStatus()
    },
    async getTags() {
      try {
        const { tags } = this.$interface.reports
        const { get } = this._
        const params = {}
        this.tagLoading = true

        const { data: response } = await tags(params)

        if (response.code !== 0) {
          throw get(response, 'msg', '')
        }
        this.tagLoading = false
        this.tags = get(response, 'data', [])
      } catch (error) {
        this.tagLoading = false
      } finally {
      }
    },
    deleteTag(tag) {
      if (!tag) return false
      this.$confirm('Are you sure to delete?','warning', {
        type: 'warning',
      })
        .then(async () => {
          const params = {
            id: tag.id,
          }
          const { data: res } = await deleteTag(params)
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.dataInfoCopy.tagList = this.dataInfoCopy.tagList&&this.dataInfoCopy.tagList.filter(
            item => item!== tag.name
          )
          this.getTags()
          this.$message.success(res.msg)
          bus.$emit('update:tags', this.tags)
        }).catch((err) => {
        })
    },
    shareWidget(widgetId, type) {
      let url = ''
      var loca = window.location
      var path = '/Widgets'
      if (type === 'MSPbots Internal') {
        // path = '/InternalWidget'
        path = '/CrossTenantWidget'
      }
      var baseUrl = loca.origin + path
      url = baseUrl + '?widgetId=' + widgetId
      const oInput = document.createElement('input')
      document.body.appendChild(oInput)
      oInput.value = url
      oInput.select()
      document.execCommand('Copy')
      oInput.remove()
      this.$message.success('Copy Success!')
    },
    validatePass(rule, value, callback) {
      let params = {
        name: this.dataInfoCopy.name.trim(),
        isNew: !this.dataInfoCopy.id,
        gadgetId: this.dataInfoCopy.gadgetId ? this.dataInfoCopy.gadgetId : '',
        businessType: this.dataInfoCopy.businessType
          ? this.dataInfoCopy.businessType
          : this.$route.path.includes('CrossTenant')
          ? 'MSPbots Internal'
          : 'Custom',
        tenantCode: this.dataInfoCopy.tenantCode
          ? this.dataInfoCopy.tenantCode
          : this.$store.state.user.tenantCode
      }
      this.$interface.reports
        .postCheckNameApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            this.isNameOk = false
            this.loading = false
            this.$message.error(res.msg)
            return callback(new Error(res.msg))
          } else {
            this.isNameOk = true
            callback()
          }
        })
        .catch(() => {})
    },
    hasSettingType(type) {
      if (
        !this.dataInfoCopy.gadgetSettingExclude ||
        this.dataInfoCopy.gadgetSettingExclude.length === 0
      ) {
        return true
      } else {
        const val = this.dataInfoCopy.gadgetSettingExclude.findIndex(
          e => e === type
        )
        if (val < 0) {
          return true
        } else {
          return false
        }
      }
    },
    updateGenerateSetting() {
      this.generateSetting(this.dataInfoCopy)
    },
    clickMode() {
      //
      this.isAdvanceMode = !this.isAdvanceMode
      if (this.isAdvanceMode === false) {
        this.language = this.dataInfo.gadgetType === 'AIChartGadget' ? 4 : 3
      }
    },
    getReportSetting() {
      var _self = this
      // _self.loading = true
      _self.showPriview = false
      _self.originDatasetId = null
      const params = {
        // businessId: _self.dataInfoCopy.businessId,
        gadgetId: _self.dataInfoCopy.gadgetId,
        includeSql: true
      }
      if (getUrlQureyParams('appId')) {
        params.appId = getUrlQureyParams('appId')
      }
      _self.$interface.reports
        .getReportSettingInfo(params)
        .then(async ({ data: res }) => {
          if (!res.data) {
            this.isNew = true
          } else {
            this.isNew = false
          }

          if (res.code !== 0) {
            return _self.$message.error(res.msg)
          }
          if (res.data) {
            if (!res.data.isPermission && res.data.isPermission !== undefined) {
            this.$router.replace({ name: '404' })
            return
            }
            if (
              window.location.pathname.includes('dashboard-') ||
              window.location.pathname.includes('scorecard-')
            ) {
              _self.$interface.um.poststatRouteAPI({
                url: `/ReportWidget?widgetId=${
                  res.data.id
                }&reportId=${getUrlQureyParams('pageid')}`
              })
            } else {
              _self.$interface.um.poststatRouteAPI({
                url: `/Widget?widgetId=${res.data.id}`
              })
            }
            _self.gadgetId = res.data.gadgetId
            _self.language = res.data.language
            _self.modelId = res.data.id
            _self.originDatasetId = res.data.datasetId
            res.data.gadgetType = _self.dataInfoCopy.gadgetType
            _self.dataInfoCopy.gadgetSetting = {
              labelFontSize: 12,
              ...res.data.gadgetSetting
            }
            _self._.merge(_self.dataInfoCopy, res.data)
            _self.updateGadget(_self.dataInfoCopy.gadgetSetting)
            _self.dataInfoCopy = Object.assign({}, _self.dataInfoCopy)
            _self.getHistoryVersionsList()
            _self.resRoleList = res.data.roleIdList
            let roleList = []
            for (var i = 0; i < res.data.roleIdList.length; i++) {
              if (
                this.fullRoleList.filter(
                  item => item.roleId === res.data.roleIdList[i]
                )[0]
              ) {
                roleList.push(res.data.roleIdList[i])
                continue
              }
            }
            this.$set(this.dataInfoCopy, 'roleIdList', roleList)
            this.$set(this.dataInfoCopy, 'tagList', res.data.tagList)
            // this.dataInfoCopy.roleIdList = roleList
            try {
              this.$refs['gadget-setting']['gadget-setting-component'].getInfo()
              if (this.$refs['gadget-setting-kpisettings']) {
                this.$refs['gadget-setting-benchmark'][
                  'gadget-setting-component'
                ].getInfo()
                this.$refs['gadget-setting-kpisettings'][
                  'gadget-setting-component'
                ].getInfo()
              }
            } catch (error) {}
            this.resetQueryInfo(_self.dataInfoCopy)
            _self.$nextTick(() => {
              try {
                _self.$refs['gadget-setting'].resetData()
                if (_self.$refs['gadget-setting-kpisettings']) {
                  _self.$refs['gadget-setting-benchmark'].resetData()
                  _self.$refs['gadget-setting-kpisettings'].resetData()
                }
                _self.$refs['querydataset'].init()
              } catch (error) {}
            })
          } else {
            if(_self.dataInfoCopy.gadgetType === 'chartgridgadget') {
              _self.$set(
                _self.dataInfoCopy,
                'roleIdList',
                await filterRole(this.$store.state.defaultRoleList.concat(['1539094477886771202','1603251831365554178','1622450047057338370']),this.fullRoleList)
              )
            }else {
              _self.$set(
                _self.dataInfoCopy,
                'roleIdList',
                await filterRole(this.$store.state.defaultRoleList.concat(['1539094477886771202','1603251831365554178']),this.fullRoleList)
              )
            }
          }
          this.$nextTick(() => {
            _self.showPriview = true
          })
          _self.loading = false
        })
    },
    saveGadget() {
      this.saveReport('save')
    },
    resetQueryInfo(dataInfoCopy) {
      this.qureyInfo = {
        orderBy: [],
        rowLimit: ''
      }
      if (dataInfoCopy && dataInfoCopy.gadgetSetting) {
        if (dataInfoCopy.gadgetSetting.datasetOrderBy) {
          this.qureyInfo.orderBy = dataInfoCopy.gadgetSetting.datasetOrderBy
        }
        if (dataInfoCopy.gadgetSetting.datasetLimit) {
          this.qureyInfo.rowLimit = dataInfoCopy.gadgetSetting.datasetLimit
        }
      }
    },
    deleteUserTempWidget() {
      if (this.isUserCloneTemplate) {
        this.$emit('deleteHandleItem', this.dataInfoCopy)
      }
      if (this.$store.state.userTemplateClone) {
        const params = {
          id: this.dataInfoCopy.id
        }
        this.$interface.reports
          .delReportSetting(params)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.$store.state.userTemplateClone = false
          })
      }
    },
    async getLinkedDashboards () {
      const { getReportByModelListApi } = this.$interface.reports
      const params = {
        gadgetId: this.dataInfo.gadgetId||this.dataInfoCopy.gadgetId,
        reuse: true
      }
      const { data: response } = await getReportByModelListApi(params)
      if (response.code !== 0) {
        throw response.msg
      }
      return response.data.length
    },
    async getLinkedBots () {
      const { getBotByDatasetListApi } = this.$interface.bots
      const params = {
        showAllTenant: false,
        dataSourceId: this.dataInfo.gadgetId||this.dataInfoCopy.gadgetId
      }
      const { data: response } = await getBotByDatasetListApi(params)
      if (response.code !== 0) {
        throw response.msg
      }
      return response.data.length
    },
    async deleteReport(data) {
      const reportNum=await this.getLinkedDashboards()
      if(reportNum){
        this.curSelected={gadgetId: this.dataInfo.gadgetId||this.dataInfoCopy.gadgetId}
        this.linkedDashboardsModalVisible=true
        return
      }
      // const botNum=await this.getLinkedDashboards()
      // if(botNum){
      //   this.curSelected={gadgetId: this.dataInfo.gadgetId||this.dataInfoCopy.gadgetId}
      //   this.linkedBotsModalVisible=true
      //   return
      // }
      try {
        await this.$confirm(
        this.$t('custom.widget.deleteconfirm'),
        this.$t('custom.widget.deleteTitle'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
        )
        const params = {
          id: this.dataInfo.id || this.dataInfoCopy.id
        }
        const { delReportSetting } = this.$interface.reports
        const { data: response } = await delReportSetting(
          params,
          this.resourceType||1
        )
        if (response.code !== 0) {
          throw response.msg
        }
        this.$message.success(response.msg)
        this.cancelReport(data)
        this.$emit('refreshDataList')
      } catch (error) {
        useErrorMessage(error)
      } finally {
      }
      
    },
    cloneReport() {
      this.curSelected={id:this.dataInfo.id||this.dataInfoCopy.id,gadgetId:this.dataInfo.gadgetId||this.dataInfoCopy.gadgetId}
      this.cloneWidgetModalVisible=true
    },
    refresh(data){
      this.$emit('refreshDataList')
      this.dataInfo={...this.dataInfo,...data}
      this.flag=false
      this.dataInfoCopy = Object.assign(
          {
            name:
              'widget_' +
              moment().utc().format('YY/MM/DD HH:mm') +
              '_' +
              this._.random(1000, 9999, false),
            roleIdList: this.$store.state.roleList
          },
          this.dataInfo
        )
      this.$nextTick(()=>{
        this.flag=true
        this.getReportSetting()
      })
    },
    cancelReport(data) {
      this.deleteUserTempWidget()
      if (this.$refs.dataForm) this.$refs.dataForm.clearValidate()
      if (this.$refs.dataForm) this.$refs.dataForm.resetFields()
      this.showSettingInternal = false
      if( data && !data.dashboard) {
        this.$emit('queryModelClosed', this.showSettingInternal)
      }
      if (this.$refs['querydataset']) {
        this.$refs['querydataset'].clearnDatasetData()
      }
      this.$emit('queryModelBeforeClosed', this.IsChanged)
      this.dialogBeforeClosed()
    },
    dimensionCheck(arr){
        arr =arr.filter(item =>item.type===1&& item.dimensions.length>0)||[]
        if(Array.isArray(arr)&&arr.length>1&&arr.some(v=>Array.isArray(v.dimensions)&&v.dimensions.length>0)){
            let dimensiondata =arr[0]
            for (let index = 0; index < arr.length; index++) {
              const element = arr[index];
              if(dimensiondata.dimensions.length !==element.dimensions.length) {
                return false
              }
              for (let i = 0; i < dimensiondata.dimensions.length; i++) {
                if(dimensiondata.dimensions[i].dbType!==element.dimensions[i].dbType || dimensiondata.dimensions[i].alias!==element.dimensions[i].alias) {
                   return false
                }
              }
            }
            return true
        }else{
          return true
        }
    },
    async applyReport() {
      try {
        if(this.dataInfo.gadgetType === 'chartgridgadget') {
          const validate = this.$refs['gadget-setting'].$refs['generateForm'].validate&&this.$refs['gadget-setting'].$refs['generateForm'].validate()
          if(!validate) {
            return this.$message.error("Invalid input.Minimum value can't exceed maximum value or Interval cannot be less than zero.")
          }
        }
      } catch (error) {
        
      }
     
      if(this.$refs['gadget-setting-kpisettings']){
        await this.$refs['gadget-setting-kpisettings'].setKpiSettings()
      }
      if(this.queryList) {
        let result=this.dimensionCheck(this.queryList)
        if(!result) {
          this.$message.error('All dimensions must be of the same alias and same field type!')
          return
        }
         if (this.dataInfoCopy&&this.dataInfoCopy.id&& this.dataInfoCopy.gadgetType==='tablegadget') {
         if(this.queryList.length>0&&this.queryList[0]&&this.queryList[0].dimensions&&Array.isArray(this.queryList[0].dimensions) && this.queryList[0].dimensions.length>2) {
           return this.$message.error("You may only add up to two dimensions")
          }
        }
      }

      if (
        this.dataInfoCopy.status === 'Published' ||
        this.dataInfoCopy.status === 'Alpha'
      ) {
        let tempList = []
        tempList = this._.filter(this.queryList, { type: 1 })
        const checkQuery = tempList.every(
          query =>
            query.datasetStatus === 'Published' ||
            query.datasetStatus === 'Alpha'
        )
        if (!checkQuery) {
          return this.$message.error(
            this.$t('custom.component.gadget.checkQuery')
          )
        }
      }

      if (
        this.$store.state.user.username.includes('mspbots.ai') &&
        Boolean(this.$hasPermission('sys:widget:moreedit'))
      ) {
        if (!this.dataInfoCopy.da) {
          return this.$message.error(this.$t('custom.component.gadget.da'))
        }
        if (!this.dataInfoCopy.po) {
          return this.$message.error(this.$t('custom.component.gadget.po'))
        }
        if (!this.dataInfoCopy.jiraNumber) {
          return this.$message.error(
            this.$t('custom.component.gadget.checkNumber')
          )
        }
      }


      if (!this.isNameOk)
        return this.$message.error('The name is already exists')
      this.saveSource = 'apply'
      this.saveReport('preview')
    },
    onDatasetChange(data) {},
    async getAssignRoleList() {
      let temp = []
      let roleList = this.$store.state.user.roleList
      roleList.forEach(it => {
        temp.push(it.id)
      })
      let params = qs.stringify(
        {
          roleId: temp
        },
        { arrayFormat: 'repeat' }
      )
      const { data: res } = await this.$interface.um.getAssignRoleList(params)
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.assignRoleList = res.data
    },
    async getRoleAssignList() {
      let temp = []
      let roleList = this.$store.state.user.roleList
      roleList.forEach(it => {
        temp.push(it.id)
      })
      let params = qs.stringify(
        {
          roleId: temp,
          tenantCode:this.$store.state.user.tenantCode
        },
        { arrayFormat: 'repeat' }
      )
      const { data: res } = await this.$interface.um.getRoleAssignListApi(params)
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.fullRoleList = res.data
    },
    inputDescriptionChange() {
      this.$forceUpdate()
    },
    saveReport(type) {
      // ==================== MB-15301 START ==================== //
      this.loading = true
      // ==================== MB-15301 END ==================== //
      if (
        this.$refs['order-by'] &&
        !this.$refs['order-by'].orderByListCheck()
      ) {
        this.loading = false
        return this.$message.error('Incorrect setting order by')
      }
      if (!this.dataInfoCopy.name) {
        this.loading = false
        return this.$message.error(this.$t('custom.report.tips.nameRequired'))
      }
      if (this.language === 3 || this.language === 4) {
        if (this.hasSettingType('DATA') && this.$refs['querydataset']) {
          this.dataInfoCopy = mergeCoverData(
            this.dataInfoCopy,
            this.$refs.querydataset.getReturnData()
          )
        }
      }
      // process title and description
      if (this.dataInfoCopy.gadgetSetting && this.dataInfoCopy.name) {
        this.dataInfoCopy.gadgetSetting.headerTitle = this.dataInfoCopy.name
        this.dataInfoCopy.gadgetSetting.headerDescription =
          this.dataInfoCopy.description
        this.dataInfoCopy.gadgetSetting.wikiUrl = this.dataInfoCopy.wikiUrl
        this.dataInfoCopy.gadgetSetting.datasetLimit = this.$refs['row-limit']
          ? this.$refs['row-limit'].getLimitValue()
            ? this.$refs['row-limit'].getLimitValue().toString()
            : ''
          : ''
        this.dataInfoCopy.gadgetSetting.datasetOrderBy = this.$refs['order-by']
          ? this.$refs['order-by'].getOrderByList()
          : []
      } else {
        var temp = {
          headerTitle: this.dataInfoCopy.name,
          headerDescription: this.dataInfoCopy.description
        }
        Object.assign({}, this.dataInfoCopy.gadgetSetting, temp)
      }
      let data = this.fillGadgetSettingFromFormSetting()
      if (!this.isAdvanceMode && typeof data !== 'boolean') {
        let findMappingFormObj = this._.find(defaultGadgetSettingList, {
          gadgetType: this.dataInfoCopy.gadgetType
        })
        if (data.then !== undefined) {
          data.then(result => {
            findMappingFormObj.mappingForm(
              this.dataInfoCopy.gadgetSetting,
              result
            )
            this.dataInfoCopy.gadgetSetting = Object.assign(
              {},
              { ...this.dataInfoCopy.gadgetSetting }
            )
            this.doSaveReport(type)
          })
        } else {
          if (this.dataInfoCopy.gadgetSetting.report === undefined) {
            this.dataInfoCopy.gadgetSetting.report = {}
          }
          findMappingFormObj.mappingForm(this.dataInfoCopy.gadgetSetting, data)
          this.dataInfoCopy.gadgetSetting = Object.assign(
            {},
            { ...this.dataInfoCopy.gadgetSetting }
          )
          this.doSaveReport(type)
        }
      } else {
        this.doSaveReport(type)
      }
    },
    verifyForm() {
      return this.$refs['dataForm'].validate()
    },
    doSaveReport(type) {
      if(this.dataInfoCopy&&this.dataInfoCopy.id&&this.dataInfoCopy.gadgetSetting) {
           if (slicerGadgetTypeList.find(i => i === this.dataInfoCopy.gadgetType)&& !this.dataInfoCopy.gadgetSetting.queryParams[0]) {
             this.loading = false
             return this.$message.error("QueryParams cannot be empty")
           }
      }
      this.verifyForm()
        .then(() => {
          let _self = this
          _self.showPriview = false
          if (_self.dataInfoCopy.gadgetType === 'pvtablegadget') {
            if (_self.$refs['gadget-preview']) {
              let obj = _self.$refs['gadget-preview'].getGadgetSetting()

              obj.showToolbar = this.dataInfoCopy.gadgetSetting.showToolbar
              obj.isEmptyCellsTextContent = this.dataInfoCopy.gadgetSetting.isEmptyCellsTextContent
              obj.showGroupingBar =
                this.dataInfoCopy.gadgetSetting.showGroupingBar
              obj.expandAll = this.dataInfoCopy.gadgetSetting.expandAll
              obj.dataSourceSettings.expandAll =
                this.dataInfoCopy.gadgetSetting.expandAll
              _self.dataInfoCopy.gadgetSetting = { labelFontSize: 12, ...obj }
            }
            _self.dataInfoCopy.gadgetSetting.headerTitle =
              this.dataInfoCopy.name
            _self.dataInfoCopy.gadgetSetting.headerDescription =
              this.dataInfoCopy.description
            _self.dataInfoCopy.gadgetSetting.wikiUrl = this.dataInfoCopy.wikiUrl
            _self.dataInfoCopy.gadgetSetting.datasetLimit = this.$refs[
              'row-limit'
            ]
              ? this.$refs['row-limit'].getLimitValue()
                ? this.$refs['row-limit'].getLimitValue().toString()
                : ''
              : ''
            _self.dataInfoCopy.gadgetSetting.datasetOrderBy = this.$refs[
              'order-by'
            ]
              ? this.$refs['order-by'].getOrderByList()
              : []
          }
          var scorecardStatus = false
          if (_self.dataInfoCopy.gadgetType === 'scorecardgadget') {
            if (
              _self.dataInfoCopy.gadgetSetting.fields &&
              _self.dataInfoCopy.gadgetSetting.fields.length > 0 &&
              _self.dataInfoCopy.gadgetSetting.refreshCron
            ) {
              scorecardStatus = true
            } else {
              scorecardStatus = false
            }
            _self.dataInfoCopy.gadgetSetting.headerTitle =
              this.dataInfoCopy.name
            _self.dataInfoCopy.gadgetSetting.headerDescription =
              this.dataInfoCopy.description
            _self.dataInfoCopy.gadgetSetting.wikiUrl = this.dataInfoCopy.wikiUrl
            _self.dataInfoCopy.gadgetSetting.datasetLimit = this.$refs[
              'row-limit'
            ]
              ? this.$refs['row-limit'].getLimitValue()
                ? this.$refs['row-limit'].getLimitValue().toString()
                : ''
              : ''
            _self.dataInfoCopy.gadgetSetting.datasetOrderBy = this.$refs[
              'order-by'
            ]
              ? this.$refs['order-by'].getOrderByList()
              : []
          }
          let params = {
            ..._self.dataInfoCopy,
            name: _self.dataInfoCopy.name.trim(),
            language: _self.language,
            type: _self.getWidgetType(_self.dataInfoCopy.gadgetType), // _self.dataInfoCopy.type ? _self.dataInfoCopy.type : 1,
            reuse: type === 'save' ? true : _self.dataInfoCopy.reuse || false,
            status: _self.dataInfoCopy.status
              ? _self.dataInfoCopy.status
              : 'Published',
            businessType: _self.dataInfoCopy.businessType
              ? _self.dataInfoCopy.businessType
              : 'Custom',
            roleIdList: _self.dataInfoCopy.roleIdList
              ? _self.dataInfoCopy.roleIdList
              : [],
            tenantCode: _self.dataInfoCopy.tenantCode
              ? _self.dataInfoCopy.tenantCode
              : this.$store.state.user.tenantCode
          }
          if(this.isAI){
            params.content = 'select * from undefined'
          }
          if (scorecardStatus) {
            this.createDataset(params)
          }
          if (
            params.gadgetType === 'pageheadergadget' &&
            getUrlQureyParams('appId')
          ) {
            params.appId = getUrlQureyParams('appId')
            params.menuList = params.gadgetSetting.menuList
            delete params.gadgetSetting.menuList
          }
          if (_self.saveSource && _self.saveSource === 'apply') {
            if (params.gadgetType !== 'pageheadergadget') {
              if (params.roleIdList.length < 1) {
                return this.$message.error('Please Assign Role')
              }
              if (_self.$hasPermission('sys:widget:widgetadmin')) {
                if (!params.status) {
                  return this.$message.error(
                    'Please Select Status (In More Edit)'
                  )
                }
                if (!params.businessType) {
                  return this.$message.error(
                    'Please Select Type (In More Edit)'
                  )
                }
              }
            }
            _self.saveSource = ''
          }
          if (params.datasetId) {
            if (_self.originDatasetId !== params.datasetId) {
              this.clearFilter()
            }
          }
          _self.IsChanged = true
          if (
            params.gadgetSetting.report &&
            params.gadgetSetting.report.groupSettings
          ) {
            params.gadgetSetting.report.groupSettings.columns =
              this.groupSettingsColumns
          }
          if (this.isUserCloneTemplate || this.$store.state.userTemplateClone) {
            params.status = 'Published'
          }
          params.resourceType = this.resourceType

          this.$interface.reports
            .postReportSetting(params)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              if (this.isUserCloneTemplate) {
                this.$emit('updateIsUserCloneTemplate', false)
              }
              if (this.$store.state.userTemplateClone) {
                this.$root.eventBus.$emit(
                  'updateTemplateId',
                  this.$store.state.userTemplateCloneId,
                  res.data
                )
                this.$store.state.userTemplateClone = false
              }
              scorecardStatus = false
              if (type === 'preview') {
                // _self.$emit('queryModelPreview')
                this.$message.success('Apply Success')
              } else {
                _self.showSettingInternal = false
                _self.$emit('queryModelClosed', _self.showSettingInternal)
                return this.$message.success(res.msg)
              }
              _self.dataInfoCopy = _self._.merge(_self.dataInfoCopy, res.data)
              _self.$nextTick(() => {
                try {
                  this.getTags()
                  _self.$refs['gadget-setting'].resetData()
                  if (_self.$refs['gadget-setting-kpisettings']) {
                    _self.$refs['gadget-setting-benchmark'].resetData()
                    _self.$refs['gadget-setting-kpisettings'].resetData()
                  }
                  _self.$refs['querydataset'].dogetQeryList()
                } catch (error) {}
              })
              this.$forceUpdate()
              _self.loading = false
              _self.showPriview = true
              this.$emit('refreshDataList', res.data)
            })
            .catch(error => {
              _self.loading = false
              _self.showPriview = true
              _self.$message.error(error)
            })
        })
        .catch(() => {
          this.loading = false
        })
    },
    getWidgetType(data) {
      let result = slicerGadgetTypeList.find(item => {
        return item === data
      })
      if (result) {
        return 2
      } else {
        return 1
      }
    },
    fillGadgetSettingFromFormSetting() {
      // getFromFormSetting
      if (typeof this.$refs['gadget-setting'].getData() !== 'boolean') {
        if (this.$refs['gadget-setting-kpisettings']) {
          return {
            ...this.$refs['gadget-setting'].getData(),
            ...this.$refs['gadget-setting-benchmark'].getData(),
            ...this.$refs['gadget-setting-kpisettings'].getData(),
          }
        }
        return this.$refs['gadget-setting'].getData()
      } else {
        return false
      }
    },
    // wait confirm
    showQueryModel() {
      this.showSettingInternal = !this.showSettingInternal
    },
    updateformSelectList() {},
    afterSettingInit() {},
    getHistoryVersionsList() {
      if (this.modelId) {
        const params = {
          type: 'sys_model',
          businessId: this.modelId
        }
        this.$interface.reports
          .getHistoryVersionsListApi(params)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.historyVersionList = res.data
          })
          .catch(() => {})
      } else {
        this.historyVersionList = []
      }
    },
    useHistoryVersion(row) {
      const id = row.id
      this.$interface.reports
        .useHistoryVersionApi(id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.showSettingInternal = false
          this.$emit('queryModelClosed', this.showSettingInternal)
          return this.$message.success(res.msg)
        })
        .catch(() => {})
    },
    emitDoSql() {
      this.showPriview = true
      this.$emit('queryModelPreview')
    },
    formatList(list) {
      if (list && list.length > 0) {
        return list.toString()
      }
    },
    updateList() {
      this.$emit('queryModelPreview')
      this.updateReportColumn()
    },
    updateReportColumn() {},
    setFieldsList(dataList) {
      let _self = this
      var tempList = []
      tempList = dataList
      if (
        _self.hasSettingType('DATA') &&
        _self.$refs['querydataset'] &&
        _self.$refs['gadget-setting']
      ) {
        if (
          _self.dataInfoCopy.gadgetType === 'gridgadget' ||
          _self.dataInfoCopy.gadgetType === 'crudformgadget' ||
          _self.dataInfoCopy.gadgetType === 'checklistgadget' ||
          _self.dataInfoCopy.gadgetType === 'hierarchygridgadget' ||
          _self.dataInfoCopy.gadgetType === 'treegridgadget' ||
          _self.dataInfoCopy.gadgetType === 'crudformplusgadget'
        ) {
          var tempStatus = false
          tempStatus = _self.$refs['querydataset'].exportLayerChange()
            ? _self.$refs['querydataset'].exportLayerChange()
            : false
          if (tempStatus === true) {
            _self.$refs['gadget-setting'].layerStatus = tempStatus
            _self.$refs['gadget-setting'].fieldsList = []
            _self.$refs['gadget-setting'].fieldsList = tempList
            _self.$refs['gadget-setting'].resetData()
          } else {
            _self.$refs['gadget-setting'].fieldsList = []
            _self.$refs['gadget-setting'].fieldsList = tempList
            _self.$refs['gadget-setting'].resetData()
          }
        } else {
          _self.$refs['gadget-setting'].fieldsList = []
          _self.$refs['gadget-setting'].fieldsList = tempList
          _self.$refs['gadget-setting'].resetData()
        }
      }
      _self.$forceUpdate()
    },
    pushColumn(name) {
      this.dataInfoCopy.gadgetSetting.report.columns.push({
        field: name,
        headerText: name,
        textAlign: 'Left',
        allowEditing: true,
        allowFiltering: true,
        allowGrouping: true,
        allowReordering: true,
        allowSearching: true,
        allowSorting: true,
        autoFit: true,
        disableHtmlEncode: false,
        enableGroupByFormat: false,
        foreignKeyField: name,
        showColumnMenu: true,
        showInColumnChooser: true,
        sortDirection: 'Descending',
        type: 'number',
        template: null,
        visible: true,
        showSetting: false
      })
    },
    // wait confirm
    filterMethod(node, keyword) {
      return node.text.toLowerCase().indexOf(keyword.toLowerCase()) !== -1
    },
    async getRoleList() {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      const { data: res } = await this.$interface.system.getClientRoleListApi(
        params
      )
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.roleList = res.data
    },
    showMoreClick() {
      this.$refs['more-edit'].visible = !this.$refs['more-edit'].visible
    },
    onchangeTabs(val, oldVal) {
      if (
        this.$store.state.user.username.includes('mspbots.ai') &&
        Boolean(this.$hasPermission('sys:widget:moreedit'))
      ) {
        if (!this.dataInfoCopy.id) {
          if (!this.dataInfoCopy.da) {
            this.$message.error(this.$t('custom.component.gadget.da'))
            return false
          }
          if (!this.dataInfoCopy.po) {
            this.$message.error(this.$t('custom.component.gadget.po'))
            return false
          }
          if (!this.dataInfoCopy.jiraNumber) {
            this.$message.error(this.$t('custom.component.gadget.checkNumber'))
            return false
          }
        }
      }
      try {
        if (val === 'condition' && this.dataInfoCopy.id) {
          this.$refs['condition-setting'].queryKeyOptions()
        }
        if (val === 'config' && this.dataInfoCopy.id) {
          this.$refs['gadget-setting'].queryKeyCURDOptions()
        }
        if (this.dataInfoCopy.gadgetType === 'pageheadergadget') {
          return true
        } else {
          if (
            (!this.dataInfoCopy.hasOwnProperty('roleIdList') ||
              this.dataInfoCopy.roleIdList.length === 0) &&
            oldVal === 'info'
          ) {
            this.$message.warning('Please assign role.')
            return false
          } else if (!this.dataInfoCopy.id) {
            this.isNewAdd = true
            // this.$message.warning('Please apply first')
            this.applyReport()
          } else {
            return true
          }
        }
      } catch (error) {
        return true
      }
    },
    dialogBeforeClosed() {
      Object.assign(this.$data, this.$options.data())
    },
    clearFilter() {
      if (!this.dataInfoCopy.gadgetId) {
        return
      }
      const params = {
        gadgetId: this.dataInfoCopy.gadgetId,
        type: 'widget'
      }
      this.$interface.reports
        .deleteFilterApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message.success(res.msg)
        })
        .catch(() => {})
    },
    showDataInspactor() {
      // let radioSelectScriptItem = this.showJson.find(e => e.type === 'radio-select') || {}
      // let type = this.dataForm[radioSelectScriptItem.text][radioSelectScriptItem.radioValue]
      // let id = this.dataForm[radioSelectScriptItem.text][radioSelectScriptItem.selectValue]
      // if (type === 'dataset') {
      //   this.datasetId = id
      // } else {
      //   this.gadgetId = id
      // }
      // let filterScriptItem = this.showJson.find(e => e.type === 'filter') || {}
      // this.filterJson = this.dataForm[filterScriptItem.text]
      // this.$nextTick(() => {
      this.$refs['preview-data'].init()
      // })
    },
    createDataset(data) {
      const params = {
        name: `snapshot create Dataset ${data.name}`,
        integration: ['TEAMS'],
        businessId: getUUID(),
        language: 'sql',
        formCode: null,
        type: 1,
        content: this.currentDatasetSql({
          gadgetId: data.gadgetId,
          fields: data.gadgetSetting.fields,
          dateInterval: data.gadgetSetting.dateInterval,
          valueFieldsX: data.gadgetSetting.valueFieldsX
        }),
        dataWarehouseLayer: 'dw',
        tenantCode: this.$store.state.user.tenantCode, // '1001'
        status: data.status,
        refreshType: 'snapshot',
        description: `dw Dataset which generated from widget '${data.name}'`,
        roleIdList: data.roleIdList,
        internalNotes: '',
        businessType: data.businessType, // Template
        rentention: null,
        refreshContent: JSON.stringify({
          gadgetId: data.gadgetId,
          tenantCode: this.$store.state.user.tenantCode,
          timezoneOffset: this.$store.state.user.timezoneOffset
        }),
        refreshCron: data.gadgetSetting.refreshCron,
        timezoneId: data.gadgetSetting.timezoneId,
        botCron: null,
        createContent: null,
        owner: null,
        cronContent: null,
        refreshName: data.gadgetId,
        datasetKey: data.gadgetId
      }
      this.$interface.reports
        .updateDatasetInfoForKeyApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
        })
    },
    currentDatasetSql(data) {
      let temp = ''
      try {
        if (
          data.dateInterval &&
          data.dateInterval !== null &&
          data.dateInterval !== undefined &&
          data.dateInterval !== ''
        ) {
          if (data.valueFieldsX && data.valueFieldsX !== 'snapshot_date') {
            temp =
              `select id, (extend->0->>'${data.valueFieldsX}')::timestamp + interval '${data.dateInterval}' as snapshot_date,extend->0->>'${data.fields[0]}' as "${data.fields[0]}" from sys_snapshot where  gadget_id='${data.gadgetId}'` +
              ' and tenant_id={tenant_code} order by sync_time'
          } else {
            temp =
              `select id, sync_time + interval '${data.dateInterval}' as snapshot_date,extend->0->>'${data.fields[0]}' as "${data.fields[0]}" from sys_snapshot where  gadget_id='${data.gadgetId}'` +
              ' and tenant_id={tenant_code} order by sync_time'
          }
        } else {
          if (data.valueFieldsX && data.valueFieldsX !== 'snapshot_date') {
            temp =
              `select id, (extend->0->>'${data.valueFieldsX}')::timestamp as snapshot_date,extend->0->>'${data.fields[0]}' as "${data.fields[0]}" from sys_snapshot where  gadget_id='${data.gadgetId}'` +
              ' and tenant_id={tenant_code} order by sync_time'
          } else {
            temp =
              `select id, sync_time as snapshot_date,extend->0->>'${data.fields[0]}' as "${data.fields[0]}" from sys_snapshot where  gadget_id='${data.gadgetId}'` +
              ' and tenant_id={tenant_code} order by sync_time'
          }
          // ${this.execSQL(data.gadgetSetting.fields)}
          // temp = `select sync_time as snapshot_date,extend->0->>'${data.fields[0]}' as "${data.fields[0]}" from sys_snapshot where  gadget_id='${data.gadgetId}'` + ' and tenant_id={tenant_code} order by sync_time'
        }
      } catch (error) {
        temp = ''
      }
      return temp
    },
    execSQL(filedsList) {
      // ERROR
      // need change add many fileds
      let temp = ''
      try {
        if (filedsList && filedsList.length > 0) {
          for (let index = 0; index < filedsList.length; index++) {
            const element = filedsList[index]
            temp += `extend->${index}->>'${element}' as ${element}`
          }
        }
      } catch (error) {
        temp = ''
      }
      return temp
    }
  },
  destroyed () {
    // this.$root.eventBus.$off('close')
    this.$off('event:setting')
  }
}
</script>

<style scoped lang="scss">
.section-setting {
  height: 70vh;
  overflow: auto;
  word-break: normal;
}

.section-preview {
  background-color: #f5f5f5;
  height: 70vh;
  padding: 20px;
  overflow: auto;
}

.el-icon {
  width: 24px;
  height: 24px;
}

.el-icon:hover {
  box-shadow: 0 0 2px 1px;
}
.el-drawer__body {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}
.tabs-pane-padding {
  padding: 0px 15px !important;
}
.info-tips {
  font-size: 12px;
  color: #000000;
  // opacity: 0.5;
  word-break: break-all;
}
</style>
<style lang="scss">
.gadget_query_model {
  .dataset-order-by {
    .sort {
      cursor: pointer;
      padding: 2px;
      margin-right: 4px;
      &:hover {
        border-radius: 50%;
        background: #17b3a3;
        color: #ffffff;
      }
    }
    .el-button--mini.is-circle {
      padding: 5px;
    }
    .el-tag {
      height: 24px;
      line-height: 24px;
      margin-right: 6px;
    }
    .el-data-default {
      padding: 0px !important;
      margin-top: 10px !important;
      margin-bottom: 10px !important;
      line-height: 20px !important;
    }

    .el-form--label-top ::v-deep .el-form-item__label {
      padding: 0px !important;
    }
    .el-cascader-panel .el-checkbox {
      width: 100%;
      height: 100%;
      z-index: 10;
      position: absolute;
      top: 0px;
      right: 10px;
    }
    .el-cascader-panel .el-checkbox__input {
      visibility: hidden;
    }
    .el-cascader-panel .el-cascader-node__postfix {
      top: 10px;
    }
    .el-dialog__body {
      overflow: auto;
    }
    ul {
      list-style: none;
      margin: 0;
      padding: 0;
    }
    li {
      list-style: none;
      margin: 0;
      padding: 0;
    }
  }

  .summarize-list li {
    height: 35px;
    background-color: #fff;
    border-radius: 5px;
    border: 1px solid #f0f0f0;
    margin: 5px 0;
    padding: 0 5px;
  }
  .el-popover .el-select {
    width: 254px;
  }
  .el-divider {
    margin: 20px 0 15px !important;
  }
  .formatType.el-select {
    width: 85%;
  }
  .queryModelDialog .el-dialog__body {
    padding-left: 0 !important;
  }
  #tab-first {
    box-shadow: 0px 0px 0px #fff !important;
  }
  #tabsList .is-active {
    background-color: rgba(230, 247, 255, 1) !important;
  }
}
.queryModelDialog {
  .el-dialog {
    margin-top: 5vh !important;
  }
  .el-dialog__body {
    padding-left: 0 !important;
  }
  #tab-first {
    box-shadow: 0px 0px 0px #fff !important;
  }
  #tabsList .is-active {
    background-color: rgba(230, 247, 255, 1) !important;
  }
  .el-form--label-top .el-form-item__label {
    padding: 0px;
  }
}
</style>
